package logic

import (
	"context"
	"user666/model/mysql"
	"user666/userrpc/internal/svc"
	"user666/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *userrpc.ListRequest) (*userrpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	quire := mysql.DB.Offset(int(offset)).Limit(int(pageSize)).Order("price")
	var findpro []mysql.Product
	quire.Find(&findpro)
	if in.Name != "" {
		quire.Where("name like ?", "%"+in.Name+"%").Find(&findpro)
	}
	var product []*userrpc.List
	for _, i2 := range findpro {
		list := userrpc.List{
			Id:     int64(i2.ID),
			Name:   i2.Name,
			Price:  float32(i2.Price),
			Number: int64(i2.Number),
			UserId: int64(i2.UserId),
			Title:  i2.Title,
		}
		product = append(product, &list)
	}

	return &userrpc.ListResponse{List: product}, nil
}
